package com.gw.booking.filter;


import com.gw.booking.common.ApiException;
import com.gw.booking.common.Constant;
import com.gw.booking.common.MessageCode;
import com.gw.booking.entity.LoginToken;
import com.gw.booking.entity.Privilege;
import com.gw.booking.service.LoginTokenService;
import com.gw.booking.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.regex.Pattern;

public class TokenInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private LoginTokenService loginTokenService;
	@Autowired
	private UserService userService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		String token = request.getHeader("token");

		if (StringUtils.equalsIgnoreCase("OPTIONS", request.getMethod())) {
			return true;
		}

		LoginToken loginToken = loginTokenService.txRefreshLoginToken(token);
		if (loginToken == null /*|| !StringUtils.equals(request.getRemoteAddr(), loginToken.getIp())*/) {
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			throw new ApiException(MessageCode.CODE_NEED_LOGIN);
		}

		String uri = StringUtils.equalsIgnoreCase("GET", request.getMethod())
				? request.getServletPath() + request.getQueryString() : request.getServletPath();
		if (!checkPrivilege(uri, loginToken)) {
			response.setStatus(HttpServletResponse.SC_FORBIDDEN);
			throw new ApiException(MessageCode.CODE_NO_PRIVILEGE);
		}

		request.setAttribute("loginToken", loginToken);

		return true;
	}

	/**
	 * 验证后台用户权限
	 */
	private boolean checkPrivilege(String uri, LoginToken loginToken) {
		//食客不需要判断权限
		if (uri.startsWith("/wechat")) {
			return StringUtils.equals(Constant.USER_TYPE_DINER, loginToken.getType());
		}
		if (uri.startsWith("/commons")) {
			return true;
		}
		if (uri.startsWith("/merchant")) {
			return StringUtils.equals(Constant.USER_TYPE_MERCHANT, loginToken.getType());
		}


		//不是后台用户，没有权限
		if (uri.startsWith("/backend") && !StringUtils.equals(Constant.USER_TYPE_BACKEND, loginToken.getType())) {
			return false;
		}

		List<Privilege> unachivedPrivileges = userService.txGetUnachivedPrivileges(loginToken.getUserId());

		if (unachivedPrivileges == null || unachivedPrivileges.isEmpty()) {
			return true;
		}

		for (Privilege privilege : unachivedPrivileges) {
			String pattern = "^" + privilege.getUrlPattern().replaceAll("\\*", ".*");
			if (Pattern.matches(pattern, uri)) {
				return false;
			}
		}

		return true;
	}
}
